package com.ai.bitcoin.service.helper;

import com.ai.bitcoin.constant.CommonConstant;
import com.ai.bitcoin.constant.MonitorSettingConstrant;
import com.ai.bitcoin.enums.MonitorSwitchTypeEnum;
import com.ai.bitcoin.jpa.dao.*;
import com.ai.bitcoin.jpa.entity.*;
import com.ai.bitcoin.jpa.service.BccArticleService;
import com.ai.bitcoin.jpa.service.BccNewsService;
import com.ai.bitcoin.redis.service.BccRedisService;
import com.ai.bitcoin.util.DateUtil;
import com.ai.bitcoin.util.JacksonUtils;
import com.ai.bitcoin.vo.*;
import com.ai.bitcoin.weixin.template.SendReportService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class NsqServiceHelper {

    @Autowired
    private BccNewsService bccNewsService;

    @Autowired
    private BccAnnoInfoCrawlDao bccAnnoInfoCrawlDao;
    @Autowired
    private BccArticleService bccArticleService;

    @Autowired
    private BccRedisService bccRedisService;

    @Autowired
    private BccUserDao bccUserDao;

    @Autowired
    private SendReportService sendReportService;

    @Autowired
    private BccNewsRecordDao bccNewsRecordDao;

    @Autowired
    private BccWeixinCoinQrcodeDao bccWeixinCoinQrcodeDao;


    @Autowired
    private BccUGooveVideoDao bccUGooveVideoDao;

    @Autowired
    private PushWxTemplateBizHelper pushWxTemplateBizHelper;

    @Autowired
    private ExchangeUserRelDao exchangeUserRelDao;

    @Autowired
    private BccReportMonitorConfigDao reportMonitorConfigDao;

    @Autowired
    private PushTemplateEsBizHelper pushTemplateEsBizHelper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //price_change_market
    public void distributorThreshhold(BoomBustQueueVO boomBustQueueVO) {
        log.info("【阀值提醒】 接收到MQ的消息实体为：{}", boomBustQueueVO);
        log.info(" ********【阀值提醒】开始 ********** ");
        String bccId = boomBustQueueVO.getBcc_id();

        // 取得满足价格界限和交易所的用户
        List<BccReportMonitorConfig> monitorMinList = reportMonitorConfigDao.findSettingMinThreshholdUser(bccId, boomBustQueueVO.getPrice());
        List<BccReportMonitorConfig> monitorMaxList = reportMonitorConfigDao.findSettingMaxThreshholdUser(bccId, boomBustQueueVO.getPrice());
        if (CollectionUtils.isNotEmpty(monitorMinList)) {
            distributorThreshholdPrice(monitorMinList, boomBustQueueVO, "MIN");
            return;
        }
        if (CollectionUtils.isNotEmpty(monitorMaxList)) {
            distributorThreshholdPrice(monitorMinList, boomBustQueueVO, "MAX");
            return;
        }

        log.info(" ********【分发价格】结束 ********** ");
    }

    /**
     * 最低价格阀值提醒
     *
     * @param monitorList     提醒人
     * @param boomBustQueueVO 价格
     * @param flag            最低 最高价格标志
     */
    private void distributorThreshholdPrice(List<BccReportMonitorConfig> monitorList, BoomBustQueueVO boomBustQueueVO, String flag) {
        Long id = pushTemplateEsBizHelper.saveEsBoomBustQueueVO(boomBustQueueVO);

        for (BccReportMonitorConfig config : monitorList) {
            if (config.getCoinPriceMarket() == null) {
                continue;
            }
            List<String> coinPriceMarketList = Lists.newArrayList(StringUtils.split(config.getCoinPriceMarket(), ","));
            if (!coinPriceMarketList.contains(boomBustQueueVO.getMarket())) {
                //交易所设置不符
                continue;
            }
            // 提醒验证
            if (!isOpenWeChatNotice(config.getOpenId())) {
                //提醒验证未通过
                continue;
            }

            // 推送报告逻辑判断
            //备注
            // 仅有效一次
            String markBuilder = "您好，当前" +
                    //交易所
                    boomBustQueueVO.getMarket() + "的" +
                    //比特币
                    config.getBccNameEn() +
                    "的价格为" + boomBustQueueVO.getPrice() + "美元，已经" + (Objects.equals(flag, "MIN") ? "低于" : "高于") + "您设定的" + config.getCoinPriceMin() + "美元" +
                    "\n" +
                    "➡点击设置更多阀值提醒";
            Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_PRICE_THRESHHOLD_CODE, config.getBccId(), markBuilder, String.valueOf(id), config.getOpenId(), null, boomBustQueueVO);
            if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                return;
            }
            log.info("【价格推送微信模板信息，参数：{}】", fillingParamMap);
            Integer coinPriceRate = config.getCoinPriceRate();
            //每天有效一次
            if (coinPriceRate == 2) {
                // 放入redis
                //最小阀值key 每天一次
                String key = "Threshhold_" + config.getOpenId() + "_" + config.getBccId() + "_" + DateUtil.currentDate2Str(CommonConstant.REPORT_HTML_PREFIX_PATH);
                String hashPushed = stringRedisTemplate.opsForValue().get(key);
                if (StringUtils.isNotEmpty(hashPushed)) {
                    log.info("【阀值提醒微信模板信息，设置价格推送仅一次的用户 openId = {},当天已经推送过阀值提醒信息】", config.getOpenId());
                    return;
                }

                // 推送微信模板消息
                sendReportService.sendTemplateMsg(fillingParamMap);
                //当日23点后失效
                stringRedisTemplate.opsForValue().set(key, MonitorSettingConstrant.PRICE_ONLY_WX_PUSH_VALUE, 24 - Calendar.getInstance().get(Calendar.HOUR_OF_DAY), TimeUnit.HOURS);
                log.info("【阀值提醒微信模板信息，仅一次条件，放入redis成功，key 为：{}，推送微信模板信息】", key);

            }
            else if (coinPriceRate == 0) {
                // 仅一次推送 推送后设置阀值为空 下次不进行推送
                sendReportService.sendTemplateMsg(fillingParamMap);
                config.setCoinPriceMin(null);
                reportMonitorConfigDao.save(config);
            }
        }
    }

    //是否可推送
    private boolean isOpenWeChatNotice(String openId) {
        BccUser user = bccUserDao.findByOpenId(openId);
        boolean isOpenWeChatNotice = true;
        switch (user.getMonitorPushType()) {
            //正常推送
            case 1:
                isOpenWeChatNotice = true;
                break;
            //夜间不推送
            case 2:
                int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                //0点到8点不推送
                isOpenWeChatNotice = hour >= 8;
                break;
            //不接受推送
            case 3:
                isOpenWeChatNotice = false;
        }

        return isOpenWeChatNotice;
    }

    public void distributorNews(News2BccVo news2BccVo) {
        log.info("【分发舆情】 接收到MQ的消息实体为：{}", news2BccVo);

        log.info(" ********【分发舆情】开始 ********** ");
        String bccId = news2BccVo.getBcc_id();

        BccNewsRecord newsRecord = new BccNewsRecord();
        newsRecord.setCreateTime(new Date());
        newsRecord.setContent(JacksonUtils.toJson(news2BccVo));
        newsRecord.setNewsId(news2BccVo.getNews_id());
        newsRecord.setBccId(news2BccVo.getBcc_id());
        newsRecord.setType(1);
        try {
            bccNewsRecordDao.save(newsRecord);
        } catch (Exception e) {
            log.info("重复事件,舆情{}", JacksonUtils.toJson(news2BccVo));
            log.info(" ********【分发舆情】结束 ********** ");
            return;
        }

        // 根据舆情Id查询舆情信息
        BccNews bccNews = bccNewsService.queryByNewsId(news2BccVo.getNews_id());
        if (null == bccNews) {
            log.info("【分发舆情】失败，没有查询到舆情任何信息，币的Id为：{}，舆情Id为：{}", news2BccVo.getBcc_id(), news2BccVo.getNews_id());
            return;
        }

        // 币的二维码链接
        BccWeixinCoinQrcode qrcode = getQrcodeUrlByBccId(news2BccVo.getBcc_id());
        if (qrcode != null) {
            bccNews.setQrcodeUrl(qrcode.getUrl());
        }

        BccGooveVideo bccGooveVideo = bccUGooveVideoDao.queryByBccId(news2BccVo.getBcc_id());
        if (null != bccGooveVideo) {
            String gooveUrl = bccGooveVideo.getGooveUrl();

            bccNews.setGooveUrl(gooveUrl);

        }


        try {
            // 缓存舆情信息
            String speechUrl = news2BccVo.getSpeech_url();
            if (StringUtils.isNotBlank(speechUrl)) {
                speechUrl = speechUrl.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
                bccNews.setSpeechUrl(speechUrl);
            }
            bccRedisService.cache2SingleBccNew(news2BccVo.getBcc_id(), news2BccVo.getNews_id(), bccNews);
        } catch (Exception e) {
            log.error("【分发舆情】缓存舆情信息失败！,异常栈信息：{}，币的Id为：{}，舆情消息Id为：{}", e.getMessage(), news2BccVo.getBcc_id(), news2BccVo.getNews_id());
        }


        List<String> subscibeBccAndSwitchOnUserOpenIds = pushWxTemplateBizHelper.getSubscibeBccAndSwitchOnUserOpenId(bccId, MonitorSwitchTypeEnum.ERC_TWO_ZERO_SWITCH);
        if (subscibeBccAndSwitchOnUserOpenIds == null || subscibeBccAndSwitchOnUserOpenIds.isEmpty()) {
            log.warn("【分发舆情，没有人订阅和打开这个开关】 bccId 为：{}", bccId);
            return;
        }

        String description = pushWxTemplateBizHelper.getRemarkByDescription(bccNews.getDescription());
        StringBuilder markBuilder = new StringBuilder();
        markBuilder.append(description)
                .append("\n")
                .append("➡点击设置更多新闻舆情提醒");
        for (String pushOpenId : subscibeBccAndSwitchOnUserOpenIds) {
            // 推送参数
            Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_NEWS_CODE, news2BccVo.getBcc_id(), markBuilder.toString(), news2BccVo.getNews_id(), pushOpenId, null, bccNews);
            if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                return;
            }
            log.info("【分发舆情推送微信模板信息，参数：{}】", fillingParamMap);
            // 推送消息
            sendReportService.sendTemplateMsg(fillingParamMap);
        }


        log.info(" ********【分发舆情】结束 ********** ");
    }


    public void distributorAnno(Anno2BccVo anno2BccVo) {
        log.info("【分发公告】 接收到MQ的消息实体为：{}", anno2BccVo);
        log.info(" ********【分发公告】开始 ********** ");
        BccNewsRecord newsRecord = new BccNewsRecord();
        newsRecord.setCreateTime(new Date());
        newsRecord.setContent(JacksonUtils.toJson(anno2BccVo));
        newsRecord.setNewsId(anno2BccVo.getAnno_id());
        newsRecord.setBccId(anno2BccVo.getBcc_id());
        newsRecord.setType(2);
        try {
            bccNewsRecordDao.save(newsRecord);
        } catch (Exception e) {
            log.info("重复事件,公告{}", JacksonUtils.toJson(anno2BccVo));
            log.info(" ********【分发公告】结束 ********** ");
            return;
        }

        // 根据公告Id查询公告信息
        Optional<BccAnnoInfoCrawl> bccAnnoInfoCrawl = bccAnnoInfoCrawlDao.findById(anno2BccVo.getAnno_id());
        if (!bccAnnoInfoCrawl.isPresent()) {
            log.info("【分发公告】失败，没有查询到公告任何信息，币的Id为：{}，公告Id为：{}", anno2BccVo.getBcc_id(), anno2BccVo.getAnno_id());
            return;
        }

        BccAnnoInfoCrawl annoInfoCrawl = bccAnnoInfoCrawl.get();

        // 币的二维码链接
        BccWeixinCoinQrcode qrcode = getQrcodeUrlByBccId(anno2BccVo.getBcc_id());
        if (qrcode != null) {
            annoInfoCrawl.setQrcodeUrl(qrcode.getUrl());
        }

        try {
            // 缓存公告信息
            String speechUrl = anno2BccVo.getSpeech_url();
            if (StringUtils.isNotBlank(speechUrl)) {
                speechUrl = speechUrl.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "");
                annoInfoCrawl.setSpeechUrl(speechUrl);
            }

            bccRedisService.cache2SingleBccAnnoInfo(anno2BccVo.getBcc_id(), anno2BccVo.getAnno_id(), annoInfoCrawl);
        } catch (Exception e) {
            log.error("【分发公告】缓存公告信息失败！,异常栈信息：{}，币的Id为：{}，分发公告舆情Id为：{}", e.getMessage(), anno2BccVo.getBcc_id(), annoInfoCrawl.getAnnoId());
        }


        // 2.订阅币和打开开关的用户的openId
        List<String> subscibeBccAndSwitchOnUserOpenIds = pushWxTemplateBizHelper.getSubscibeBccAndSwitchOnUserOpenId(anno2BccVo.getBcc_id(), MonitorSwitchTypeEnum.EXCHANGE_ANNO_SWITCH);
        if (subscibeBccAndSwitchOnUserOpenIds == null || subscibeBccAndSwitchOnUserOpenIds.isEmpty()) {
            log.warn("【分发公告，没有人订阅和打开这个开关】 bccId 为：{}", anno2BccVo.getBcc_id());
            return;
        }

        // 3.用户配置这个币在这条消息的交易所中
        List<ExchangeUserRel> userRelList = exchangeUserRelDao.queryWithMarket(subscibeBccAndSwitchOnUserOpenIds, anno2BccVo.getDomain());
        if (userRelList == null || userRelList.isEmpty()) {
            log.warn("【分发公告，订阅和打开开关的人中，没有人配置币的交易所在推送的交易所: {} 中】", anno2BccVo.getDomain());
            return;
        }

        List<String> pushOpenIds = userRelList.stream().map(ExchangeUserRel::getOpenId).collect(Collectors.toList());
        // 4.开始推送，微信暴涨暴跌模板信息
        log.info("【开始推送，微信《分发公告》模板信息】bccId为：{}， 推送的用户有：{}", anno2BccVo.getBcc_id(), pushOpenIds);

        for (String pushOpenId : pushOpenIds) {
            // 推送参数
            Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_EXCHANGE_ANNO_CODE, anno2BccVo.getBcc_id(), MonitorSettingConstrant.DEFAULT_REMARK, anno2BccVo.getAnno_id(), pushOpenId, anno2BccVo.getDomain(), annoInfoCrawl);
            if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                return;
            }
            log.info("【分发公告推送微信模板信息，参数：{}】", fillingParamMap);
            // 推送微信模板消息
            sendReportService.sendTemplateMsg(fillingParamMap);
        }
        log.info(" ********【分发公告】结束 ********** ");
    }


    /**
     * 获取币的二维码链接
     *
     * @param bccId
     * @return
     */
    public BccWeixinCoinQrcode getQrcodeUrlByBccId(String bccId) {
        return bccWeixinCoinQrcodeDao.findByBccId(bccId);
    }


    /**
     * 暴涨暴跌
     *
     * @param bustQueueVO
     */
    public void distributorBoomBust(BoomBustQueueVO bustQueueVO) {
        log.info("【暴涨暴跌】 接收到MQ的消息实体为：{}", bustQueueVO);

        // 1.判断价格变化的百分比是否达到配置阈值
        BigDecimal rate = bustQueueVO.getPrice_change_rate();

        if (rate == null) {
            rate = bustQueueVO.getPrice()
                    .subtract(bustQueueVO.getPrice_previous())
                    .divide(bustQueueVO.getPrice_previous().multiply(BigDecimal.valueOf(100)), 2, BigDecimal.ROUND_HALF_UP);
        }
        bustQueueVO.setPrice_change_rate(rate);
        int priceChangeRateValue = rate.abs().intValue();

        String bccId = bustQueueVO.getBcc_id();
        String market = bustQueueVO.getMarket();
        Long id = pushTemplateEsBizHelper.saveEsBoomBustQueueVO(bustQueueVO);
        if (id == null) {
            log.warn("【取消 微信《暴涨暴跌》模板推送信息】原因是：数据保存到ES中失败");
            return;
        }

        // 未达到阈值，不进行推送
        if (priceChangeRateValue < MonitorSettingConstrant.BOOM_BUST_PUSH_PERCENT_THREE) {
            log.warn("【暴涨暴跌接收到的消息未进行推送】,上次监控价格【{}】当前价格【{}】,比率【{}%】未达到推送阈值【{}%】", bustQueueVO.getPrice_previous(), bustQueueVO.getPrice(), rate, MonitorSettingConstrant.BOOM_BUST_PUSH_PERCENT_THREE);
            return;
        }

        //保存暴涨暴跌信息
        bccArticleService.saveBoomBust(id, bustQueueVO);

        log.info("【暴涨暴跌开始进行进行推送,bcc={},交易所:{}】,上次监控价格【{}】当前价格【{}】,比率【{}%】 已经达到推送阈值【{}%】", bccId, bustQueueVO.getMarket(), bustQueueVO.getPrice_previous(), bustQueueVO.getPrice(), rate, MonitorSettingConstrant.BOOM_BUST_PUSH_PERCENT_THREE);

        // 2.订阅币和打开开关的用户的openId
        List<String> subscibeBccAndSwitchOnUserOpenIds = pushWxTemplateBizHelper.getSubscibeBccAndSwitchOnUserOpenId(bccId, MonitorSwitchTypeEnum.BOOM_BUST_SWITCH);
        if (subscibeBccAndSwitchOnUserOpenIds != null && subscibeBccAndSwitchOnUserOpenIds.size() > 0) {
            log.info("【暴涨暴跌开始进行进行推送,bcc={},交易所:{}】,打开开关以及订阅的用户:{}", bccId, bustQueueVO.getMarket(), subscibeBccAndSwitchOnUserOpenIds);
            // 3.用户配置这个币在这条消息的交易所中
            List<ExchangeUserRel> userRelList = exchangeUserRelDao.queryWithMarket(subscibeBccAndSwitchOnUserOpenIds, market);
            if (userRelList == null || userRelList.isEmpty()) {
                log.warn("【暴涨暴跌，订阅和打开开关的人中，没有人配置币的交易所在推送的交易所: {} 中】", market);
                return;
            }
            List<String> pushOpenIds = userRelList.stream().map(ExchangeUserRel::getOpenId).collect(Collectors.toList());
            // 4.开始推送，微信暴涨暴跌模板信息
            log.info("【暴涨暴跌开始进行进行推送,bcc={},交易所:{}】,推送的用户:{}", bccId, bustQueueVO.getMarket(), pushOpenIds);

            BigDecimal changePrice = bustQueueVO.getPrice().subtract(bustQueueVO.getPrice_previous());
            String priceUpOrDown = "上升";
            if (changePrice.compareTo(BigDecimal.ZERO) < 0) {
                priceUpOrDown = "下降";
            }

            StringBuilder markBuilder = new StringBuilder();
            markBuilder.append("当前filecoin价格：¥").append(bustQueueVO.getPrice())
                    .append("\n")
                    .append("5分钟变化幅度超过").append(rate).append("%")
                    .append("\n")
                    .append("价格").append(priceUpOrDown).append(changePrice.abs())
                    .append("\n")
                    .append("价格波动较大，请密切关注行情走向，做好风险控制");


            for (String pushOpenId : pushOpenIds) {
                Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_BOOM_BUST_CODE, bustQueueVO.getBcc_id(), markBuilder.toString(), String.valueOf(id), pushOpenId, bustQueueVO.getMarket(), bustQueueVO);
                if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                    return;
                }
                log.info("【暴涨暴跌开始进行进行推送,bcc={},交易所:{}】,推送参数:{}", bccId, bustQueueVO.getMarket(), fillingParamMap);
                // 推送微信模板消息
                sendReportService.sendTemplateMsg(fillingParamMap);
            }
        }
    }


    /**
     * 买点，卖点
     *
     * @param buyerQueueVo
     */
    public void distributorBuyer(BuyerQueueVo buyerQueueVo) {
        log.info("【买点卖点】 接收到MQ的消息实体为：{}", buyerQueueVo);
        String bccId = buyerQueueVo.getBcc_id();

        Long id = pushTemplateEsBizHelper.saveEsBuyerSellPoint(buyerQueueVo);
        if (id == null) {
            log.warn("【取消 微信《买点卖点》模板推送信息】原因是：数据保存到ES中失败");
            return;
        }

        // 2.订阅币和打开开关的用户的openId
        List<String> subscibeBccAndSwitchOnUserOpenIds = pushWxTemplateBizHelper.getSubscibeBccAndSwitchOnUserOpenId(bccId, MonitorSwitchTypeEnum.BUYER_SELLER_POINT_SWITCH);
        if (subscibeBccAndSwitchOnUserOpenIds == null || subscibeBccAndSwitchOnUserOpenIds.isEmpty()) {
            log.warn("【买点卖点推送，没有人订阅和打开这个开关】 bccId 为：{}", bccId);
            return;
        }

        log.info("【开始推送，微信《买点卖点》模板信息】bccId为：{}， 推送的用户有：{}", buyerQueueVo.getBcc_id(), subscibeBccAndSwitchOnUserOpenIds);

        //达到占比后保存ERC20信息
        bccArticleService.saveBuySellPoint(id, buyerQueueVo);

        String reachStatus = "卖点";
        if (buyerQueueVo.getReach_low().equals("1")) {
            // 到达买点
            reachStatus = "买点";
        }
        String monitorObject = pushWxTemplateBizHelper.getMonitorObject(bccId);
        StringBuilder markBuilder = new StringBuilder();
        DecimalFormat df = new DecimalFormat("0.00");
        Double aDouble = Double.valueOf(buyerQueueVo.getCurrent_rate());
        markBuilder.append("您好，当前").append(monitorObject).append("价格为¥").append(df.format(aDouble))
                .append("，已经到达该币的最佳").append(reachStatus)
                .append("\n")
                .append("➡点击设置更多交易价格提醒");

        for (String pushOpenId : subscibeBccAndSwitchOnUserOpenIds) {
            Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_BUYER_SELLER_POINT_CODE, buyerQueueVo.getBcc_id(), markBuilder.toString(), String.valueOf(id), pushOpenId, null, buyerQueueVo);
            if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                return;
            }
            log.info("【买点卖点推送微信模板信息，参数：{}】", fillingParamMap);
            // 推送微信模板消息
            sendReportService.sendTemplateMsg(fillingParamMap);
        }
    }


    /**
     * erc20
     *
     * @param ercTwoZeroQueueVO
     */
    public void distributorErcTwoZero(ErcTwoZeroQueueVO ercTwoZeroQueueVO) {
        //无bccId直接抛出
        if (StringUtils.isEmpty(ercTwoZeroQueueVO.getBcc_id())) {
            return;
        }

        log.info("【erc20】 接收到MQ的消息实体为：{}", ercTwoZeroQueueVO);

        String bccId = ercTwoZeroQueueVO.getBcc_id();

        String circulationPercent = "";
        try {
            circulationPercent = pushWxTemplateBizHelper.computeCirculationPercent(bccId, ercTwoZeroQueueVO.getVolume());
        } catch (Exception e) {
            log.error("【计算流通占比，返回结果为空】");
        }
        ercTwoZeroQueueVO.setCirculationPercent(circulationPercent);
        String txHash = pushTemplateEsBizHelper.saveEsErcTwoZero(ercTwoZeroQueueVO);
        if (StringUtils.isEmpty(txHash)) {
            log.warn("【取消 微信《erc20》模板推送信息】原因是：数据保存到ES中失败");
            return;
        }

        //  流通占比阈值
        if (StringUtils.isEmpty(circulationPercent)) {
            log.debug("【计算流通占比，返回结果为空，不推送erc20微信模板】");
            return;
        }

        boolean erc20Threshold = pushWxTemplateBizHelper.compareErc20Threshold(circulationPercent);
        if (!erc20Threshold) {
            log.warn("【流通占比没有达到设置阈值，不推送erc20微信模板】 流通占比: {}，阈值：{}", circulationPercent, MonitorSettingConstrant.ERC_TWO_ZERO_PERCENT);
            return;
        }

        //达到占比后保存ERC20信息
        bccArticleService.saveErc20(txHash, ercTwoZeroQueueVO);

        // 2.订阅币和打开开关的用户的openId
        List<String> subscibeBccAndSwitchOnUserOpenIds = pushWxTemplateBizHelper.getSubscibeBccAndSwitchOnUserOpenId(bccId, MonitorSwitchTypeEnum.ERC_TWO_ZERO_SWITCH);
        if (subscibeBccAndSwitchOnUserOpenIds == null || subscibeBccAndSwitchOnUserOpenIds.isEmpty()) {
            log.warn("【erc20，没有人订阅和打开这个开关】 bccId 为：{}", bccId);
            return;
        }


        StringBuilder markBuilder = new StringBuilder();

        String fromName = StringUtils.isEmpty(ercTwoZeroQueueVO.getFrom_name()) ? "" : "(" + ercTwoZeroQueueVO.getFrom_name() + "交易所)";
        String toName = StringUtils.isEmpty(ercTwoZeroQueueVO.getTo_name()) ? "" : "(" + ercTwoZeroQueueVO.getTo_name() + "交易所)";
        markBuilder.append("转账金额：").append(ercTwoZeroQueueVO.getVolume()).append("个")
                .append("\n")
                .append("占流通比例：").append(circulationPercent) // 流通比例
                .append("\n")
                .append("转出地址：").append(ercTwoZeroQueueVO.getFrom_address()).append(fromName)
                .append("\n")
                .append("转入地址：").append(ercTwoZeroQueueVO.getTo_address()).append(toName)
                .append("\n")
                .append("➡点击设置更多交易信息推送");

        for (String pushOpenId : subscibeBccAndSwitchOnUserOpenIds) {
            Map<String, Object> fillingParamMap = pushWxTemplateBizHelper.fillingParamMap(MonitorSettingConstrant.MONITOR_TRANSFER_BIG_MONEY_CODE, ercTwoZeroQueueVO.getBcc_id(), markBuilder.toString(), String.valueOf(txHash), pushOpenId, null, ercTwoZeroQueueVO);
            if (fillingParamMap == null || fillingParamMap.isEmpty()) {
                return;
            }
            log.info("【erc20推送微信模板信息，参数：{}】", fillingParamMap);
            // 推送微信模板消息
            sendReportService.sendTemplateMsg(fillingParamMap);
        }
    }

}
